# -*- coding: utf8 -*-
# tests.py
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip sentinel instance
* limit
* channels
* url
"""
import hashlib, random, re, time
from util.functions import escape_for_regexp, join_userlist, gooquote
from core.ircfuncs import quiet_nick
from util.pywikilib import WikiLink, Site, Page, Time, time_diff
from util.xplor import Xplorer
from core.optimizers import File, Dicts
from dateutil.relativedelta import relativedelta as timedelta
from datetime import datetime
field = "tests"

def features_(bot, evt, cmd):
	for k, v in bot._features.iteritems():
		msg = "%s: %s" %(k, v)
		bot.reply(evt, msg)
		time.sleep(5)
features_.rule = ("features")

def error_(bot, evt, cmd):
	msg+=""
error_.rule = "error"

def parse_(bot, evt, cmd):
	bot.reply(evt, "cmd.params: %s, cmd.args: %s", str(cmd.parameters), cmd.arguments)
	bot.reply(evt, "cmd.items: %s", cmd.opts)
parse_.rule="parse"
parse_.limit=9
parse_.channels={"##bots-ca": "parseja", "##botzilla": "(?#re)quarteja"}

def old_sitematrix(bot, evt, cmd):
	file = os.path.join(os.getcwd(),"sitematrix.log")
	if os.path.exists(file) and cmd.arguments:
		jsontext = open(file,"r").read()
		codes = json.loads(jsontext)
		if cmd.arguments:
			code = cmd.arguments
			if code in codes:
				bot.reply(evt, codes[code][0])
	else:
		params ={
			"action": "sitematrix",
		}
		sm = Browser.get_api(params)
		number = sm['sitematrix']['count']
		codes={}
		for id in sm['sitematrix']:
			if id.isdigit():
				code = sm['sitematrix'][id]['code']
				name = sm['sitematrix'][id]['name']
				families = sm['sitematrix'][id]['site']
				fam=[]
				for family in families:
					fam.append(family['code'])
				codes[code]=(name, fam)
			if id=="specials":
				for proj in sm['sitematrix'][id]:
					code = proj['code']
					domain = proj['url'][7:]
					codes[code]=(domain,["special"])
		f = open(file,"w")
		json.dump(codes, f, indent=4, encoding="utf-8")
		f.close()
		if cmd.arguments:
			code = cmd.arguments
			if code in codes:
				bot.reply(evt, codes[code][0])

		bot.reply(evt, "%s :  %s" %( url,number))
old_sitematrix.rule="sitematrix"
old_sitematrix.url="http://meta.wikimedia.org/w/api.php?format=jsonfm&action=sitematrix"

def colours(bot, evt, cmd):
	args = cmd.arguments
	clr_dict={
		#http://www.mirc.com/colors.html
		"00": "white",		#w
		"01": "black",		#b
		"02": "blue",		#+l
		"03": "green",		#+e
		"04": "red",		#r
		"05": "brown",		#n
		"06": "purple",		#p
		"07": "orange",		#o
		"08": "yellow",		#y
		"09": "light_green",#e
		"10": "teal",		#t
		"11": "aqua",		#c
		"12": "light_blue",	#l
		"13": "pink",		#k
		"14": "grey",		#g
		"15": "light_grey",	#+g
	}
	colors = [u"\03%s %s %s\x0f" %(k, k, clr_dict[k]) for k in sorted(clr_dict.keys())]
	bot.reply(evt, ", ".join(colors))
colours.rule="clr"

def say(bot, evt, cmd):
	bot.reply(evt, cmd.arguments)
say.rule="say"

def revert(bot, evt, cmd):
	print "ARGUMENTS", cmd.arguments
	title = cmd.arguments[0]
	endid = cmd.arguments[1]
	wiki = WikiLink(title, evt.lang, evt.fam)
	title, site = wiki.title(), wiki.site()
	print "SITE", site, "TITLE", title
	page = Page(site, title)
	bot.reply(evt,  ",".join(page.reverts(endid)))
revert.rule = "rv"

def editors(bot, evt, cmd):
	""".eds <page> - Returns the editors of a page."""
	title = cmd.arguments
	wiki = WikiLink(title, evt.lang, evt.fam)
	title, site = wiki.title(), wiki.site()
	page = Page(site, title)
	l, c, d, n = page.editors()
	l = list(l)
	l = join_userlist(l, bot.channels[evt.chan].lang)
	bot.reply(evt, u"%s. &B;Creador:&N; %s" % (l,c))
	bot.reply(evt, u"%s" % page.title())
editors.rule = "eds"

def clear_screen(bot, evt, cmd):
	from platform import platform as pf
	from os import system as prompt
	if "Windows" in pf():
		prompt("cls")
	else:
		prompt("clear")
clear_screen.rule = "clrscr"

def O_(bot, evt, cmd):
	"""no cmd assumed"""
	return True
O_.rule = ["o", "0"]

def timestamp(bot, evt, cmd):
	if re.search("\d+.\d{1,4}", cmd.arguments):
		bot.reply(evt, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(cmd.arguments))))
timestamp.rule = "ts"

def tinyurl(bot, evt, cmd):
	"""
	http://json-tinyurl.appspot.com/?url=http://uk.wikipedia.org/w/index.php?diff=8999771&oldid=8991294
	"""

def chanstats(bot, evt, cmd):
	stats = bot.stats.get()
	if evt.chan == bot.defchan:
		for ch in stats:
			bot.reply(evt, "&B;%s:&N; &l;%i&N; %s", ch, stats[ch][0], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(stats[ch][1]))))
	elif stats.has_key(evt.chan):
		bot.reply(evt, "&B;%s:&N; &l;%i&N; %s", evt.chan, stats[evt.chan][0], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(stats[evt.chan][1]))))
	else:
		bot.reply(evt, "no such channel.")
chanstats.rule = "chstats"

def algorithm(bot, evt, cmd):
	length = int(cmd.opts["l"]) \
		if cmd.opts["l"] and isinstance(cmd.opts["l"], basestring) and cmd.opts["l"].isdigit() \
		else 8
	if length < 1: length = 1
	if (cmd.arguments and cmd.arguments.strip() == "rnd") or cmd.opts['rnd']:
		algo = ''.join(random.choice('0123456789abcdefABCDEF') for i in range(length))
	elif cmd.opts["l"] and cmd.opts["md5"]:
		if length > 32: bot.reply(evt, "md5 length is a 32-alphanumeric hash")
		algo = hashlib.md5(cmd.opts['md5']).hexdigest()
		algo = algo[:length]
	elif cmd.opts["md5"]:
		algo = hashlib.md5(cmd.opts['md5']).hexdigest()
	else:
		return False

	bot.reply(evt, algo)
algorithm.rule=  "algo"

def conv_time(bot, evt, cmd):
	usrinput = cmd.arguments
	if "." in usrinput and usrinput.replace(".","").isdigit(): usrinput=float(usrinput)
	t = Time(usrinput)
	if cmd.opts['add']:
		u, tp = cmd.opts['add'].split(" ") if " " in cmd.opts['add'] else (cmd.opts['add'], "h")
		t = Time(t.add(int(u), tp))
	elif cmd.opts['subst']:
		u, tp = cmd.opts['subst'].split(" ") if " " in cmd.opts['subst'] else (cmd.opts['subst'], "h")
		t = Time(t.subtract(int(u), tp))
	if cmd.opts['api']:
		t = t.to_api()
	else:
		t = t.to_string()
	bot.reply(evt, t)
conv_time.rule="ctime"

def nicks(bot, evt, cmd):
	print "NICKS"
	u = bot.channels[evt.chan].users()
	m = cmd.arguments or None
	for nick in bot.nicks:
		if m:
			if nick == m:
				bot.reply(evt, "&B;%s:&N; %s &+g;is identified:&N; %s" % (quiet_nick(nick, u), quiet_nick(bot.nicks[nick], u), not(" " in bot.nicks[nick])))
		else:
			bot.reply(evt, "&B;%s:&N; %s &+g;is identified:&N; %s" % (quiet_nick(nick, u), quiet_nick(bot.nicks[nick], u), not(" " in bot.nicks[nick])))
nicks.rule="nicks"
nicks.thread=True

def test_chan_(bot, evt, cmd):
	if bot.channels.has_key(cmd.arguments):
		del bot.channels[cmd.arguments]
		bot.reply(evt, "channel deleted.")
test_chan_.rule="tchan"
